package com.blue.dao.impl;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import com.blue.dao.AdminDAO;
import com.blue.pojo.Admin;

import java.io.*;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class AdminDAOImpl implements AdminDAO {
    @Override
    public List<Admin> selectAdmins() throws SQLException {
        List<Entity> entityList = Db.use().query( "SELECT * FROM t_admin " );
        List<Admin> adminList = new ArrayList<>();
        for (Entity entity : entityList) {
            adminList.add( convertAdmin( entity ) );
        }
        return adminList;
    }

    @Override
    public Admin getAdminByAccount(String account) {
        Admin admin = new Admin();
        Properties properties = new Properties();
        String path = System.getProperty( "user.dir" ) + "/user/user.properties";
        FileInputStream in = null;
        try {
            in = new FileInputStream( new File( path ) );
            properties.load( in );
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String account1 = properties.getProperty( "account" );
        if (account1 != null && account1.equals( account )) {
            String password = properties.getProperty( "password" );
            admin.setPassword( password );
            admin.setAccount( account1 );
        }
        return admin;
    }

    @Override
    public int countAdmins() throws SQLException {
        return Db.use().queryNumber( "SELECT COUNT(*) FROM t_admin " ).intValue();
    }

    @Override
    public int updateAdmin(Admin admin) throws SQLException {
        return Db.use().update(
                Entity.create().set( "password", admin.getPassword() ),
                Entity.create( "t_admin" ).set( "id", admin.getId() )
        );
    }

    /**
     * 封装一个将Entity转换为Admin的方法
     *
     * @param entity
     * @return
     */
    private Admin convertAdmin(Entity entity) {
        Admin admin = new Admin();
        admin.setId( entity.getLong( "id" ) );
        admin.setAccount( entity.getStr( "account" ) );
        admin.setPassword( entity.getStr( "password" ) );
        admin.setName( entity.getStr( "name" ) );
        admin.setAvatar( entity.getStr( "avatar" ) );
        return admin;
    }
}
